import classnames from 'classnames'
import { useEffect, useState } from 'react'
import Group, {useStore, Provider} from './group'

import './index.scss'

export interface RadioProps {
  checked?: boolean,
  defaultChecked?: boolean,
  disabled?: boolean,
  value?: any,
  onChange?: React.ChangeEventHandler<HTMLInputElement>
  children?: React.ReactNode
}

export default function Radio(props: RadioProps) {
  // 这里后续要判断是否有值，可能为 null
  const store = useStore()
  const {
    defaultChecked = false,
    checked = false,
    disabled = false,
    value,
    onChange = () => {},
    children
  } = props
  
  const [_value, setValue]  = useState(value)

  function onChangeHandler() {
    if (store) {
      store.setCurrent(_value)
    }
  }

  useEffect(() => {
    setValue(value)
  }, [value])

  let _checked = checked || defaultChecked

  if (store) {
    _checked = store.current === _value
  }
  
  const radioCls = classnames('radio', {
    checked: _checked
  })
  const innerCls = classnames('radio-inner', {
    checked: _checked
  })
  return (
    <label className='radio-wrapper checked'>
      <span className={radioCls}>
        <input 
          type='radio' 
          className='radio-input' 
          onChange={store ? onChangeHandler : onChange} 
          value={value} 
          checked={_checked} 
        />
        <span className={innerCls}></span>
      </span>
      {children ? <span>{children}</span> : null}
    </label>
  )
}

Radio.group = Group